//
//  AppDelegate.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//

#import <UMPush/UMessage.h>
#import <UMCommon/UMCommon.h>
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
#import <UserNotifications/UserNotifications.h>
#endif
#import "AppDelegate.h"
#import "MainViewController.h"
#import "OALoginViewController.h"
#import "AppDelegate+Extendion.h"
#import "MainTabBarController.h"
#import "MenuViewController.h"
#import "LockController.h"
#import "IQKeyboardManager.h"
#define UMAppKey @"5b6be6aeb27b0a0f5400001a"

#import "BaseModel.h"
@interface AppDelegate ()<UNUserNotificationCenterDelegate>


@end
@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[UMConfigure initWithAppkey:UMAppKey channel:@"App Store"];

 // Push组件基本功能配置

   [UNUserNotificationCenter currentNotificationCenter].delegate= self;

 UMessageRegisterEntity* entity = [[UMessageRegisterEntity alloc] init];

 //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标等

//    entity.types= UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert;

    [UNUserNotificationCenter currentNotificationCenter].delegate= self;

    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError* _Nullableerror) {

 if(granted) {

 // 用户选择了接收Push消息

        }else{

 // 用户拒绝接收Push消息

        }

    }];


short port = 443;                        //vpn设备端口号，一般为443
NSString *vpnIp =    @"122.224.123.170";  //vpn设备IP地址
 self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds] ;
 
 [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
 [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
 [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
 if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"shoushi"] isEqualToString:@"Y"]) {
  LockController *lockController = [[LockController alloc]init];
         self.window.rootViewController = lockController;
}else{
 
 
 
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
//    _helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
//    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
[NSThread sleepForTimeInterval:2.0];
//
//      MainViewController * mainVC = [storyBoard instantiateViewControllerWithIdentifier:@"MainVC"];
//        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:mainVC];
//         self.window.rootViewController = navVC;

 MenuViewController *tar = [[MenuViewController alloc]init];



// MainTabBarController *tar = [[MainTabBarController alloc]init];
    
                   self.window.rootViewController = tar;
                     }else{
        OALoginViewController * loginVC = [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];
        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                 self.window.rootViewController = navVC;

        loginVC.navigationController.navigationBar.hidden = YES;
    }
  }

    [self.window makeKeyAndVisible];
    [self dismissKeyBoard];
    return YES;
}
-(void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo fetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler

{

    [UMessage setAutoAlert:NO];

 //统计点击数

   [UMessage didReceiveRemoteNotification:userInfo];

 if([[[UIDevice currentDevice] systemVersion]intValue] < 10){

        [UMessage didReceiveRemoteNotification:userInfo];

 //    self.userInfo = userInfo;

 //    //定制自定的的弹出框

 //    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)

 //    {

 //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题"

 //                                                            message:@"Test On ApplicationStateActive"

 //                                                           delegate:self

 //                                                  cancelButtonTitle:@"确定"

 //                                                  otherButtonTitles:nil];

 //

 //        [alertView show];

 //

 //    }

        completionHandler(UIBackgroundFetchResultNewData);

    }

}
-(void)userNotificationCenter:(UNUserNotificationCenter*)center willPresentNotification:(UNNotification*)notification withCompletionHandler:(void(^)(UNNotificationPresentationOptions))completionHandler{

 NSDictionary* userInfo = notification.request.content.userInfo;

 if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {

 //应用处于前台时的远程推送接受

 //关闭U-Push自带的弹出框

        [UMessage setAutoAlert:NO];

 //必须加这句代码

        [UMessage didReceiveRemoteNotification:userInfo];

    }else{

 //应用处于前台时的本地推送接受

    }

 //当应用处于前台时提示设置，需要哪个可以设置哪一个

    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);

}

-(void)userNotificationCenter:(UNUserNotificationCenter*)center didReceiveNotificationResponse:(UNNotificationResponse*)response withCompletionHandler:(void(^)())completionHandler{

 NSDictionary* userInfo = response.notification.request.content.userInfo;

 if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {

 //应用处于后台时的远程推送接受

 //必须加这句代码

        [UMessage didReceiveRemoteNotification:userInfo];

    }else{

 //应用处于后台时的本地推送接受

    }

}


-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
  if (![deviceToken isKindOfClass:[NSData class]]) return;

    const unsigned *tokenBytes = [deviceToken bytes];

    NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",

                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),

                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),

                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];

    NSLog(@"deviceToken:%@",hexToken);
    // 获取用户偏好设置对象
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    // 保存用户偏好设置
            [defaults setObject:hexToken forKey:@"deviceToken"];

//
    [defaults synchronize];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//    int ssl_vpn_quit();


}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

  


}

@end
